package com.tg.paw.ums.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.ums.dto.RolePermissionDto;
import com.tg.paw.ums.entity.Role;
import com.tg.paw.ums.entity.RolePermissionRelation;
import com.tg.paw.ums.service.IRolePermissionRelationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Rubble
 * @date 2020/6/17
 */
@Slf4j
@Api("角色权限管理")
@RestController
@RequestMapping("/role")
public class ApiRoleController {

    @Autowired
    private IRolePermissionRelationService rolePermissionRelationService;

    @PostMapping("/updateRolePermission")
    public CommonResult updateRolePermission(@Valid @RequestBody RolePermissionDto rolePermissionDto, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return CommonResult.validateFailed(bindingResult);
        }
        RolePermissionRelation condition = new RolePermissionRelation();
        condition.setRoleId(rolePermissionDto.getRoleId());
        QueryWrapper<RolePermissionRelation> queryWrapper = new QueryWrapper<>(condition);
        rolePermissionRelationService.remove(queryWrapper);
        List<Long> permissions = rolePermissionDto.getPermissions();
        if(CollectionUtil.isNotEmpty(permissions)){
            List<RolePermissionRelation> list = new ArrayList<>();
            for (Long permissionId:
                permissions) {
                RolePermissionRelation record = new RolePermissionRelation();
                record.setRoleId(rolePermissionDto.getRoleId());
                record.setPermissionId(permissionId);
                list.add(record);
            }
            rolePermissionRelationService.saveBatch(list);
        }

        return CommonResult.success();
    }

    @ApiOperation("角色权限 树的选择项")
    @GetMapping("/rolePermissions")
    public CommonResult getRolePermissions(Long roleId){
        RolePermissionRelation condition = new RolePermissionRelation();
        condition.setRoleId(roleId);
        QueryWrapper<RolePermissionRelation> queryWrapper = new QueryWrapper<>(condition);
        List<RolePermissionRelation> relationList = rolePermissionRelationService.list(queryWrapper);
        List<Long> collect = relationList.stream().map(RolePermissionRelation::getPermissionId).collect(Collectors.toList());

        return CommonResult.success(collect);
    }

}
